#
Swift3 的gcd变化很大,这里列举一下,大家可以有个对照:
1、Create a serial queue 创建一个serial queue
OC
1 | dispatch_queue_t queue = dispatch_queue_create("com.leacode.gcd.serialqueue", DISPATCH_QUEUE_SERIAL); dispatch_async(queue, ^{ |
Swift3
1 | let queue = DispatchQueue(label: "com.leacode.gcd.serialqueue") |
2、Create a concurrent queue 创建一个concurrent queue
OC
1 | dispatch_queue_t concurrentQueue = dispatch_queue_create("com.leacode.gcd.concurrentqueue", DISPATCH_QUEUE_CONCURRENT); |
Swift3
1 | let queue = DispatchQueue(label: "com.leacode.gcd.concurrentqueue", attributes: [.concurrent]) |
3.系统提供的Concurrent Dispatch Queue:
从ios8开始苹果引入了一个新的概念 QoS(quality of service),有了更贴近使用场景的描述以及更细致的划分,代码如下
OC
1 | if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { |
Swift3
1 | if #available(iOS 8.0, *) { |
4.dispatch_after
这部分Swift3的变化较大
OC
1 | dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3ull * NSEC_PER_SEC); |
Swift3
1 | let time = DispatchTime.now() + 3 |
5.挂起和恢复
OC
1 | dispatch_suspend(queue); |
Swift3
1 | queue.suspend() |
6.判断间隔一段时间group是否执行结束
OC
1 | dispatch_queue_t queue1 = dispatch_queue_create("com.leacode.gcd.queue1", DISPATCH_QUEUE_SERIAL); |
Swift3
1 | let queue1 = DispatchQueue(label: "com.leacode.group.queue1") |
7.dispatch_once
这里我们用单例来举例,oc和swift中都是通过创建一个static对象来创建单例子,在swift3中只需要写一个static变量就可以了:
OC
1 | + (id)sharedInstance |
Swift
1 | class MyClass { |
在swift中已经取消掉dispatch_once了,可以看苹果的说明链接
The free function dispatch_once
is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once
provided
可以通过设置懒加载的全局属性或者静态属性来达到线程安全且执行一次的效果。